<script setup lang="ts">
import {onMounted, ref, watch} from "vue";
import router from "@/router";
import {getEmptyPost, getPostDetails, increaseViewCount, Post} from "@/net/controller/post-controller.ts";
import {ChatLineSquare, Star, View} from "@element-plus/icons-vue";
import {getComments} from "@/net/controller/comment-controller.ts";

const currentPostId = () => {
  return Number.parseInt(location.pathname.split("/")[location.pathname.split("/").length - 1])
}

const postId = ref(currentPostId())
const post = ref<Post>(getEmptyPost())
const comments = ref<Comment[]>([])
const commentsCurrentPage = ref(1)
const commentsTotal = ref(0)

watch(router.currentRoute, async () => {
  postId.value = currentPostId()
  await increaseViewCount(postId.value)
})

function updateComments(page: number) {
  getComments(postId.value, page).then((res) => {
    comments.value = res.records
    commentsTotal.value = res.total
  })
}

onMounted(async () => {
  await increaseViewCount(postId.value)

  post.value = await getPostDetails(postId.value)
})


</script>

<template>
  <main class="flex flex-vertical">
    <!-- 帖子标题-->
    <h1>{{ post.title }}</h1>

    <!-- 帖子信息栏 -->
    <div>
      <p class="flex flex-horizontal flex-center-vertically"><Clock class="icon" />于 {{ post.createdAt }} 发布</p>
      <div class="flex flex-horizontal" style="gap: .5rem">
        <div class="icon-box flex flex-horizontal flex-center-vertically">
          <View class="icon" />{{ post.viewCount}} 阅读
        </div>
        <div class="icon-box flex flex-horizontal flex-center-vertically">
          <Star class="icon" />{{ post.viewCount}} 赞
        </div>
        <div class="icon-box flex flex-horizontal flex-center-vertically">
          <ChatLineSquare class="icon" />{{ post.viewCount}} 评论
        </div>
      </div>
    </div>

    <!-- 帖子正文 -->
    <div v-html="post.content" style="margin: 1rem 0" />

    <!-- 评论区 -->
    <p class="section-title">评论</p>

    <div v-for="(comment, index) in comments">
      {{ comment }}
    </div>

    <el-pagination layout="prev, pager, next"
                   style="margin-top: 1rem"
                   size="default"
                   :page-size="20"
                   :total="commentsTotal"
                   v-model:current-page="commentsCurrentPage"
                   @current-change="updateComments"
    />

    <span style="height: 4rem" />
  </main>
</template>

<style scoped>
.section-title {
  font-size: 18px;
}

.icon-box {
  color: #999;
}

.icon {
  width: 16px;
  height: 16px;
  margin-right: .25rem
}

</style>